import React, { useState } from 'react';
import { fetchAlphaData } from '../../api/alpha';
import './StockAlphaChart.scss';

const Alpha = () => {
  console.log("✅ Alpha 页面加载成功");
  const [stockCode, setStockCode] = useState('');
  const [chartData, setChartData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!stockCode) return;
    
    setIsLoading(true);
    try {
      const data = await fetchAlphaData(stockCode);
      setChartData(data);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="alpha-container">
      <h1 className="page-title">股票因子分析与最大回撤</h1>
      
      <form onSubmit={handleSubmit} className="query-form">
        <div className="input-group">
          <input
            type="text"
            value={stockCode}
            onChange={(e) => setStockCode(e.target.value)}
            placeholder="输入股票代码 (如: 600000)"
            className="stock-input"
          />
          <button 
            type="submit" 
            className="query-button"
            disabled={isLoading}
          >
            {isLoading ? '查询中...' : '查询'}
          </button>
        </div>
      </form>

      {isLoading && (
        <div className="loading-text">加载中...</div>
      )}

      {chartData && (
        <div className="chart-section">
          <h2>股票 {chartData.stockCode} 因子分析与最大回撤</h2>
          <div className="chart-container">
            <img 
              src={chartData.image} 
              alt={`${chartData.stockCode}因子分析图`} 
              className="chart-image"
            />
          </div>
          <p className="update-time">
            最后更新时间: {new Date(chartData.timestamp).toLocaleString()}
          </p>
        </div>
      )}
    </div>
  );
};

export default Alpha;